<template>
	<view class="root">
		<view
			v-for="(section, index) in model"
			:key="index"
			class="br-20 oh"
			:style="{ margin: `20rpx` }"
		>
			<block v-for="(option, key) in section" :key="key">
				<image
					v-if="option.el === 'image'"
					:style="{ width: `100%`, height: `280rpx` }"
					:src="option.value || `/static/img/pic-addPhoto.png`"
					mode="aspectFill"
					@click="chooseImage(index, key)"
				/>

				<label
					v-if="['input', 'switch'].includes(option.el)"
					class="height-90 pl-20 pr-20 bgc-fff jc-sb"
				>
					<text class="color-333 fs-30 fw-600">{{ option.title }}：</text>

					<switch
						v-if="option.el === 'switch'"
						:checked="option.value"
						color="#f45455"
						@change="changeSwitch($event, index, key)"
					/>
					<input
						v-if="option.el === 'input'"
						class="ml-30 fs-28 f1 input"
						:type="option.type"
						:placeholder="option.placeholder"
						:maxlength="option.maxlength"
						:value="option.data"
						@input="inputValue($event, index, key)"
						placeholder-style="color: #999"
					/>
				</label>

				<view v-if="option.el === 'textarea'">
					<text class="color-333 fs-30 fw-600 pl-20 pr-20">{{ option.title }}：</text>
					<textarea
						class="mt-20 fs-28 fw-400 bgc-fff br-20"
						:style="{
							height: `180rpx`,
							width: `auto`,
							padding: `20rpx`,
							lineHeight: 1.5,
						}"
						:maxlength="option.maxlength"
						:value="option.data"
						:placeholder="option.placeholder"
						@input="inputValue($event, index, key)"
						placeholder-style="color: #999"
					/>
				</view>
			</block>
		</view>
		<view
			:class="[
				`bgc-fff safe-area-inset-bottom content-box jc-center fixed bottom-0 width-100percent`,
			]"
			:style="{ height: `120rpx` }"
		>
			<button
				hover-class="tap-hover"
				:style="{
					margin: `0 24rpx`,
					backgroundImage: `linear-gradient(to right, #f45455, #ff7b6f)`,
				}"
				class="fs-34 color-fff fw-500 lh-90"
				@click="submit"
			>
				提交
			</button>
		</view>
	</view>
</template>

<script lang="ts">
	import { Vue, Component } from "vue-property-decorator";
	import { Storage, sleep } from "@/static/libs/utils";

	@Component
	export default class SetCommodity extends Vue {
		// component property

		commodityInfo: AnyObject = {};
		get model(): AnyObject[] {
			const { commodityInfo } = this;
			return [
				{
					banner: {
						el: "image",
						placeholder: "请上传商品图片",
						value: commodityInfo.cover_image,
						data: commodityInfo.cover_image,
						name: "cover_image",
					},
				},
				{
					name: {
						el: "input",
						title: "商品名称",
						maxlength: 90,
						type: "text",
						placeholder: "请输入商品名称",
						data: commodityInfo.name,
						name: "name",
					},
					price: {
						el: "input",
						title: "商品价格",
						maxlength: 6,
						type: "digit",
						placeholder: "请输入商品价格",
						data: commodityInfo.price,
						name: "price",
					},
					stock: {
						el: "input",
						title: "商品库存",
						maxlength: 6,
						type: "number",
						placeholder: "请输入商品库存",
						data: commodityInfo.stock,
						name: "stock",
					},
					recommend: {
						el: "switch",
						title: "设为首页推荐",
						value: !!+commodityInfo.status,
						data: commodityInfo.status || 1,
						name: "status",
					},
				},
				{
					description: {
						el: "textarea",
						title: "商品描述",
						maxlength: 300,
						placeholder: "请输入商品描述",
						data: commodityInfo.des,
						name: "des",
					},
				},
			];
		}
		commodity_id: number | void;
		category_id: number | void;

		onLoad({ category_id, commodity_id }: AnyObject) {
			this.category_id = +category_id;
			if (!commodity_id) return;
			this.commodity_id = +commodity_id;
			this.$request
				.get("/shop/productDetail", { id: commodity_id })
				.then(({ data }) => (this.commodityInfo = data));
		}
		async chooseImage(index: number, key: string) {
			const [chooseFail, chooseRes]: any = await uni.chooseImage({ count: 1 });
			if (chooseFail) return;
			const option = this.model[index][key];

			const [uploadFail, uploadRes]: any = await uni.uploadFile({
				url: this.$config.API_URL + "/common/upload",
				name: "file",
				filePath: chooseRes.tempFilePaths[0],
				formData: {
					// #ifdef MP-WEIXIN
					...uni.getAccountInfoSync().miniProgram,
					// #endif
				},
				header: { token: Storage.get("authorizationInfo")?.token },
			});
			if (uploadFail) {
				uni.showToast({ icon: "none", title: uploadFail.errMsg });
				return;
			}

			const { data, code, msg: title } = JSON.parse(uploadRes.data);
			if (code !== 1) {
				uni.showToast({ title, icon: "none" });
				return;
			}
			option.value = chooseRes.tempFilePaths[0];
			option.data = data.url;
			this.$forceUpdate();
			uni.hideLoading();
		}

		inputValue({ detail }: AnyObject, index: number, key: string) {
			const option = this.model[index][key];
			option.data = detail.value;
		}

		changeSwitch({ detail }: AnyObject, index: number, key: string) {
			const option = this.model[index][key];

			option.value = detail.value;
			option.data = (+detail.value).toString();
		}

		submit() {
			const flatModel: AnyObject = {};

			this.model.forEach((item) =>
				Object.keys(item).forEach((key) => (flatModel[key] = item[key]))
			);

			const params: AnyObject = {},
				verify: boolean = Object.values(flatModel).every((item) => {
					params[item.name] = item.data;
					!item.data && uni.showToast({ title: item.placeholder, icon: "none" });
					return Boolean(item.data);
				});
			if (!verify) return;
			uni.showLoading({ title: "Loading..." });
			this.$request
				.post("/shop/editProduct", {
					id: this.commodity_id,
					cate_id: this.category_id,
					...params,
				})
				.then(async ({ msg: title }) => {
					uni.showToast({ title, duration: 1000, mask: true });
					await sleep(1);
					uni.navigateBack({});
				});
		}
	}
</script>

<style lang="scss" scoped>
	// scss
</style>